package swim.sessionbeans;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;

import swim.entitybeans.Abilita;
import swim.entitybeans.Macroarea;
import swim.entitybeans.NuovaAbilita;
import swim.entitydata.DatiRichiesteAbilita;

@Stateless
@RemoteBinding(jndiBinding="AdminRemote")
public class Admin implements AdminRemote{

	@PersistenceContext(unitName = "swim")
	private EntityManager manager;
	
	@Override
	public List<DatiRichiesteAbilita> getListaRichiesteNuoveAbilita() {
		Query q = manager.createQuery("SELECT na FROM NuovaAbilita na");
		List<DatiRichiesteAbilita> list = new ArrayList<DatiRichiesteAbilita>();
		for(Object na: q.getResultList()){
			list.add(new DatiRichiesteAbilita(((NuovaAbilita)na).getId().toString(),((NuovaAbilita)na).getNome(),((NuovaAbilita)na).getDescrizione()));
		}
		return list;
	}

	@Override
	public void inserisciAbilita(String id_macro, String nome) {
		Abilita abilita = new Abilita();
		abilita.setMacroarea(manager.find(Macroarea.class, id_macro));
		abilita.setNome(nome);
		manager.persist(abilita);
	}

	@Override
	public void inserisciMacroarea(String id_macro) {
		Macroarea macroarea = new Macroarea();
		macroarea.setNome(id_macro);
		manager.persist(macroarea);		
	}
	
	@Override
	public Long loginAdmin(String user, String password) {
		Query q = manager.createQuery("SELECT id FROM Amministratore WHERE email_login='"+user+"' AND password='"+password+"'");
		if(q.getResultList().size()==1){
			return (Long) q.getSingleResult();
		}else{
			return -1L;
		}
	}

	@Override
	public List<String> getMacroareaList() {
		Query q = manager.createQuery("SELECT nome FROM Macroarea");
		List<String> list = castList(String.class, q.getResultList());

		return list;
	}

	@Override
	public void cancellaRichiesta(String id) {
		NuovaAbilita ra = manager.find(NuovaAbilita.class, Long.valueOf(id));
		manager.remove(ra);		
	}
	
	private <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
		List<T> r = new ArrayList<T>(c.size());
		for (Object o : c)
			r.add(clazz.cast(o));
		return r;
	}
	
}
